package com.dujiu.interceptor;

import com.dujiu.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    public JwtInterceptor(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        log.debug("Authorization Header: {}", authHeader);

        // 1. 检查Authorization头是否存在且格式正确
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            log.warn("Missing or invalid Authorization header");
            sendError(response, "Missing or invalid Authorization header");
            return false;
        }

        // 2. 提取token
        String token = authHeader.substring(7).trim();
        if (token.isEmpty()) {
            log.warn("Empty token in Authorization header");
            sendError(response, "Empty token");
            return false;
        }

        // 3. 校验token
        try {
            if (!jwtUtil.validateToken(token)) {
                log.warn("Invalid token: {}", token);
                sendError(response, "Invalid token");
                return false;
            }
            // 校验通过
            log.debug("Token validated successfully.");
            return true;
        } catch (Exception e) {
            log.error("Token validation error", e);
            sendError(response, "Token validation error: " + e.getMessage());
            return false;
        }
    }

    private void sendError(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("{\"error\":\"" + message + "\"}");
    }
}
